package com.testdemo.common.base;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentManager;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;

import com.lzy.okgo.OkGo;
import com.testdemo.MyApplication;
import com.testdemo.R;
import com.testdemo.common.utils.CommonUtil;
import com.testdemo.common.utils.InputMethodTools;
import com.testdemo.common.utils.ToastUtil;
import com.testdemo.common.view.SimpleDialog;
import com.testdemo.common.view.TitleBar;

import java.util.ArrayList;

import de.greenrobot.event.EventBus;

/**
 * Created by dell on 2017/11/20.
 */

public class BaseActivity extends AppCompatActivity implements TitleBar.OnTitleBarClickListener {

    public static int ACTION_GET_PERMISSION = 15894;

    public Context mContext;
    public BaseActivity mActivity;
    public FragmentManager mFragmentManager;
    public LoadingDialog dialog;

    public TitleBar mTitleBar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.e("UiClassName:", getClass().getSimpleName());
        MyApplication.getInstance().addActivity(this);
        EventBus.getDefault().register(this);
        mContext = getApplicationContext();
        mActivity = this;
        mFragmentManager = getSupportFragmentManager();

        //设置为竖屏
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

        //沉浸式
        adaptTheme(true);
//        statusBarLightMode(this);

    }




    /**
     * 收起软键盘
     */
    public void hideKeyboard() {
        InputMethodTools.HideKeyboard(getWindow().getDecorView());
    }


    @Override
    public void setContentView(int layoutResID) {
        super.setContentView(layoutResID);
        setFitsSystemWindows(true);
        mTitleBar = (TitleBar) findViewById(R.id.titleBar);
        if (mTitleBar != null) {
            mTitleBar.setOnTitleBarClickListener(this);
        }
    }

    public void setContentView(int layoutResID, boolean isFitsSystemWindows) {
        super.setContentView(layoutResID);
        setFitsSystemWindows(isFitsSystemWindows);
        mTitleBar = (TitleBar) findViewById(R.id.titleBar);
        if (mTitleBar != null) {
            mTitleBar.setOnTitleBarClickListener(this);
        }
    }

    public void onEventMainThread(Object event) {

    }

    /**
     * 设置布局内容和状态栏不重合
     *
     * @param fitsSystemWindows
     */
    public void setFitsSystemWindows(boolean fitsSystemWindows) {
        ViewGroup contentFrameLayout = (ViewGroup) findViewById(Window.ID_ANDROID_CONTENT);
        View parentView = contentFrameLayout.getChildAt(0);

        if (parentView != null && Build.VERSION.SDK_INT >= 14) {
            parentView.setFitsSystemWindows(fitsSystemWindows);
        }
    }


    boolean isShowing = false;


    /**
     * 透明状态栏
     */
    @TargetApi(Build.VERSION_CODES.KITKAT)
    public void adaptTheme(final boolean isTranslucentStatusFitSystemWindowTrue) {
        if (isTranslucentStatusFitSystemWindowTrue) {
            Window window = getWindow();
            window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            //状态栏设置为全透明//目标版本在26的时候，22以上版本的手机需要如下代码才能全透明
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS
                        | WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
                window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
//                        | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION  //加个这个下面的虚拟状态栏 布局也会沉浸进去
                        | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
                window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
                window.setStatusBarColor(Color.TRANSPARENT);
                window.setNavigationBarColor(CommonUtil.getColor(R.color.grey_c8c9cc));
            }
        }
    }

//    /**
//     * 透明状态栏
//     */
//    @TargetApi(Build.VERSION_CODES.KITKAT)
//    public void adaptTheme(final boolean isTranslucentStatusFitSystemWindowTrue) {
//        if (isTranslucentStatusFitSystemWindowTrue) {
//            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
//                getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
//            }
//        }
//    }


//    /**
//     * **********  不需要黑色字体的直接重写这个方法把代码干掉  ***********
//     * 设置状态栏黑色字体图标，
//     * 6.0以上版本Android
//     */
//    public void statusBarLightMode(Activity activity) {
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
//            activity.getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
//        }
//    }

    /**
     * 显示弹窗
     */
    public void showProgressDialog() {
        showProgressDialog(true);
    }

    /**
     * 判断是否显示
     *
     * @return
     */
    public boolean isShowingProgressDialog() {
        if (null != dialog) {
            return dialog.isShowing();
        } else {
            return false;
        }
    }

    public void showProgressDialog(boolean cancelable) {
        try {
            if (dialog == null) {
                dialog = new LoadingDialog(this, mFragmentManager);
                dialog.setCancelable(cancelable);
                if (!isFinishing() && !isShowing) {
                    isShowing = true;
                    dialog.show();
                }
                dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                    @Override
                    public void onCancel(DialogInterface dialog) {
                        isShowing = false;
                        dialog.cancel();
                        onProgressDialogCancelByUser();
                    }
                });
            } else if (!isShowing && !isFinishing()) {
                if (!dialog.isAdded()) {
                    isShowing = true;
                    dialog.show();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 隐藏弹窗
     */
    public void dismissProgressDialog() {
        try {
            if (dialog != null && isShowing) {
                isShowing = false;
                dialog.dismiss();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 当用户按返回键取消了等待框
     */
    public void onProgressDialogCancelByUser() {
        OkGo.getInstance().cancelTag(this);
    }


    @Override
    public void onBackClick() {//标题栏返回键被点击
        onBackPressed();
    }

    @Override
    public void onRightClick() {//标题栏右边的文字或者图标被点击

    }

    /**
     * 动态权限的获取被允许了
     */
    public void onPermissionsGot(int requestCode) {

    }

    /**
     * 动态权限的获取被取消了
     */
    public void onPermissionsCancel(int requestCode) {
        ToastUtil.showText("您拒绝了授予权限");
    }

    public void getPermissions(int requestCode, @NonNull String... permissions) {
        ArrayList<String> requestPermissions = new ArrayList<>();
        for (String permission : permissions) {
            if (ContextCompat.checkSelfPermission(MyApplication.myApplication, permission) == PackageManager.PERMISSION_DENIED) {//没有权限
                requestPermissions.add(permission);
            }
        }
        if (requestPermissions.isEmpty()) {
            onPermissionsGot(requestCode);
        } else {
            String[] strings = new String[requestPermissions.size()];
            for (int i = 0; i < requestPermissions.size(); i++) {
                strings[i] = requestPermissions.get(i);
            }
            ActivityCompat.requestPermissions(this, strings, ACTION_GET_PERMISSION);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == ACTION_GET_PERMISSION) {
            for (int i = 0; i < grantResults.length; i++) {
                if (grantResults[i] != 0) {//没有被允许
                    //检测到有拒绝时打勾了的情况，直接弹框去设置页面让用户设置
                    if (!ActivityCompat.shouldShowRequestPermissionRationale(mActivity, permissions[i])) {
                        new SimpleDialog(this)
                                .setTitleText("前往设置页面授予权限")
                                .setConfirmButtonText("确定")
                                .setCancelButtonText("取消")
                                .setOnConfirmListener(new SimpleDialog.OnConfirmListener() {
                                    @Override
                                    public void onConfirm(DialogInterface dialog) {
                                        dialog.dismiss();
                                        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                                        intent.setData(Uri.parse("package:" + getPackageName())); // 根据包名打开对应的设置界面
                                        startActivity(intent);
                                    }
                                }).show();
                        return;
                    }
                    onPermissionsCancel(requestCode);
                    return;
                }
            }
            onPermissionsGot(requestCode);
        }
    }

    public void start(Class<? extends Activity> activityClass) {
        Intent intent = new Intent();
        intent.setClass(MyApplication.getInstance(), activityClass);
        this.startActivity(intent);
    }

    public void start(Class<? extends Activity> activityClass, int requestCode) {
        Intent intent = new Intent();
        intent.setClass(this, activityClass);
        this.startActivityForResult(intent, requestCode);
    }

    public void start(Intent i, int requestCode) {
        this.startActivityForResult(i, requestCode);
    }

    public void start(Class<? extends Activity> activityClass, BaseIntent baseIntent) {
        Intent intent = new Intent();
        intent.setClass(this, activityClass);
        baseIntent.setIntent(intent);
        this.startActivity(intent);
    }

    public void start(Class<? extends Activity> activityClass, BaseIntent baseIntent, int requestCode) {
        Intent intent = new Intent();
        intent.setClass(this, activityClass);
        baseIntent.setIntent(intent);
        this.startActivityForResult(intent, requestCode);
    }


    public interface BaseIntent {
        void setIntent(Intent intent);
    }

    @Override
    protected void onDestroy() {
        hideKeyboard();
        EventBus.getDefault().unregister(this);
        MyApplication.myApplication.removeActivity(this);
        OkGo.getInstance().cancelTag(this);
        super.onDestroy();
    }
}
